package com.wdl.sm.webui.security;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SUserRepository repository;

    /*
    @RequestMapping("/user")
    @ResponseBody
    public Map<String, Object> user(Principal user) {
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("name", user.getName());
        map.put("roles", AuthorityUtils.authorityListToSet(((Authentication) user).getAuthorities()));
        return map;
    }
    */

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> login(@RequestBody Map<String, String> input) {
        Map<String, String> userInfo = new HashMap<String, String>();

        if (null == input) {
            userInfo.put("reason", "用户输入为空");
            return userInfo;
        }

        String userName = input.get("userName");

        if (userName == null || userName.isEmpty()) {
            userInfo.put("reason", "用户名输入为空");
            return userInfo;
        }

        LOG.info("Get login request with " + userName);
        SUser user = this.repository.findByName(userName);
        if (user == null) {
            userInfo.put("reason", "用户不存在");
            return userInfo;
        }

        userInfo.put("name", userName);
        userInfo.put("role", user.getRole());

        return userInfo;
    }
}
